package vip

import (
	"context"
	"fmt"
	"net/http"
	"strconv"
	"time"

	"github.com/google/uuid"

	"2106A-zg6/baidu/gateway/internal/svc"
	"2106A-zg6/baidu/gateway/internal/types"
	"2106A-zg6/baidu/gateway/internal/util"
	"2106A-zg6/baidu/srv/baiduclient"
	"2106A-zg6/baidu/srv/utils"

	"github.com/zeromicro/go-zero/core/logx"
)

type GetVipLogic struct {
	logx.Logger
	ctx    context.Context
	svcCtx *svc.ServiceContext
}

func NewGetVipLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetVipLogic {
	return &GetVipLogic{
		Logger: logx.WithContext(ctx),
		ctx:    ctx,
		svcCtx: svcCtx,
	}
}

func (l *GetVipLogic) GetVip(req *types.UserGetVip) (resp *types.Response, err error) {

	util.RedisClient()
	//util.Rdb.

	//  获取 用户ID
	value := l.ctx.Value("custom-key")

	var totalAmount int64
	var vipId int64
	switch req.Roues {
	case "一":
		totalAmount = 15
		vipId = 1
	case "二":
		totalAmount = 20
		vipId = 2
	case "三":
		totalAmount = 50
		vipId = 1
	case "四":
		totalAmount = 65
		vipId = 2
	case "五":
		totalAmount = 128
		vipId = 1
	case "六":
		totalAmount = 288
		vipId = 2
	}

	//检查 vip 成员 是否 充足
	store, err := l.svcCtx.BaiduSrv.VipStore(l.ctx, &baiduclient.VipStoreRequest{
		VipId: vipId,
	})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: http.StatusAccepted,
			Data: nil,
		}, err
	}
	utils.LogFile(fmt.Sprintf("%v", value) + "检查 库存是足够")

	//库存不足 解决方案
	if store.Store == 0 {
		return &types.Response{
			Msg:  "vip成员已满！！！后台库存不足！！！（正在增加库存，请稍后）",
			Code: http.StatusAccepted,
			Data: nil,
		}, nil
	}

	//当前时间戳 加 随机 字符窜
	orderNo := fmt.Sprintf("%v%v", uuid.NewString(), time.Now().Unix())
	//主题
	subject := "成为vip" + fmt.Sprintf("%v", time.Now().Unix())

	//使用 自身的 余额 //查询 用户信息
	info, err := l.svcCtx.BaiduSrv.GetUserInfo(l.ctx, &baiduclient.UserInfoRequest{
		UserId: fmt.Sprintf("%v", value),
	})
	if err != nil {
		return nil, err
	}

	atoi, _ := strconv.Atoi(info.UserInfo.UserBalance)
	if int64(atoi) <= totalAmount {
		//选择 支付宝支付
		return &types.Response{
			Msg:  "账户余额不足，可以选择 支付宝支付",
			Code: http.StatusAccepted,
			Data: nil,
		}, nil
	}

	atoi -= int(totalAmount)
	userId, _ := strconv.Atoi(fmt.Sprintf("%v", value))

	//扣减 用户余额
	_, err = l.svcCtx.BaiduSrv.UserBalance(l.ctx, &baiduclient.UserBalanceRequest{
		UserId:  int64(userId),
		Balance: strconv.Itoa(atoi),
	})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: http.StatusAccepted,
			Data: nil,
		}, err
	}
	//日志 文件 记录
	utils.LogFile(fmt.Sprintf("%v", value) + "余额 扣减完成")

	//下单 成功 成为 vip
	file, err := l.svcCtx.BaiduSrv.ChangeVip(l.ctx, &baiduclient.ChangeVipRequest{
		UserId:      fmt.Sprintf("%v", value),
		TotalAmount: strconv.FormatInt(totalAmount, 10),
		OrderNo:     orderNo,
	})
	if err != nil {
		return &types.Response{
			Msg:  err.Error(),
			Code: http.StatusAccepted,
			Data: nil,
		}, err
	}
	//日志 文件 记录
	utils.LogFile(fmt.Sprintf("%v", value) + "余额 扣减完成 下单")

	//生成 支付地址
	utils.AliPayInit()
	pay, err := utils.AliPay(subject, strconv.FormatInt(totalAmount, 10), orderNo)
	if err != nil {
		return nil, err
	}

	//购买成功 之后 根据用户所购买的信息 给用户 加积分
	if vipId == 1 {
		inte, _ := strconv.Atoi(info.UserInfo.UserIntegral)
		inte += 10
		l.svcCtx.BaiduSrv.UserIntegral(l.ctx, &baiduclient.UserIntegralRequest{
			UserId:   int64(userId),
			Integral: fmt.Sprintf("%d", inte),
		})
	} else if vipId == 2 {
		inte, _ := strconv.Atoi(info.UserInfo.UserIntegral)
		inte += 100
		l.svcCtx.BaiduSrv.UserIntegral(l.ctx, &baiduclient.UserIntegralRequest{
			UserId:   int64(userId),
			Integral: fmt.Sprintf("%d", inte),
		})
	}

	return &types.Response{
		Msg:  "Change Vip successful",
		Code: http.StatusOK,
		Data: map[string]interface{}{
			"PayUrl":    pay,
			"orderInfo": file,
		},
	}, nil
}
